package com.lgy.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.lgy.config.JmsConfig;
import com.lgy.jms.Producer;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/test")
public class MyTestController {
    @Autowired
    private Producer producer;

    @PostMapping("/sendMessage")
    public String sendMessage(String s) {
        Message message = new Message(JmsConfig.TOPIC, JmsConfig.MQ_BROADCAST_TAG, ("test:" + s).getBytes());
        JSONObject result = null;
        //发送
        try {
            SendResult sendResult = producer.getProducer().send(message);
            result = JSONUtil.parseObj(sendResult);
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "发送成功," + result.toString();
    }
    @PostMapping("/myTest")
    public String myTest() {
        List<String> mesList = new ArrayList<>();
        mesList.add("小小1");
        mesList.add("爸爸1");
        mesList.add("妈妈1");
        mesList.add("爷爷1");
        mesList.add("奶奶1");
        //总共发送五次消息
        int i = 0;
        for (String s : mesList) {
            //创建生产信息
            //Message message = new Message(JmsConfig.TOPIC, "testtag", ("小小一家人的称谓:" + s).getBytes());
            Message message = new Message(JmsConfig.TOPIC, JmsConfig.MQ_BROADCAST_TAG, ("小小一家人的称谓:" + s).getBytes());
            message.setKeys("s--->" + i);
            i++;
            //发送
            try {
                SendResult sendResult = producer.getProducer().send(message);
                JSONObject result = JSONUtil.parseObj(sendResult);

                System.out.println(result);
            } catch (MQClientException e) {
                e.printStackTrace();
            } catch (RemotingException e) {
                e.printStackTrace();
            } catch (MQBrokerException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return "over";
    }
}
